package concurrence;

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock demo
 */
public class LockDemo {
    private static ReentrantLock lock = new ReentrantLock();

    private static ExecutorService executor = Executors.newFixedThreadPool(100);

    private static CountDownLatch countDownLatch = new CountDownLatch(100);

    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            executor.submit(() -> count(lock, countDownLatch));
        }
        countDownLatch.await();
        System.out.println("count = " + count);
    }

    public static void count(ReentrantLock lock, CountDownLatch countDownLatch) {
        lock.lock();
        try {
            count++;
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            countDownLatch.countDown();
        }
    }

    public static void count(ReentrantLock lock) {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

}
